package com.cskaoyan.gateway.controller.user;
import com.alibaba.fastjson.JSON;
import com.mall.commons.result.ResponseData;
import com.mall.commons.result.ResponseUtil;
import com.mall.commons.tool.utils.CookieUtil;
import com.mall.user.IKaptchaService;
import com.mall.user.ILoginService;
import com.mall.user.annotation.Anoymous;
import com.mall.user.constants.SysRetCodeConstants;
import com.mall.user.dto.KaptchaCodeRequest;
import com.mall.user.dto.KaptchaCodeResponse;
import com.mall.user.dto.UserLoginRequest;
import com.mall.user.dto.UserLoginResponse;
import com.mall.user.intercepter.TokenIntercepter;
import org.apache.dubbo.config.annotation.Reference;
import org.springframework.web.bind.annotation.*;

import javax.servlet.http.Cookie;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.util.Map;

@Anoymous
@RestController
@RequestMapping("/user")
public class LoginController {
    @Reference(timeout = 3000,check = false)
     IKaptchaService ikaptchaService;
    @Reference(timeout = 3000,check = false)
     ILoginService loginService;

     @PostMapping("/login")
    public ResponseData login( Map<String,String> map, HttpServletRequest request, HttpServletResponse response){
         String userName = map.get("userName");
         String userPwd = map.get("userPwd");
         String captcha = map.get("captcha");
        //验证验证码
         KaptchaCodeRequest KaptchaCodeRequest= new KaptchaCodeRequest();
         String uuid = CookieUtil.getCookieValue(request,"captcha_uuid");
         KaptchaCodeRequest.setUuid(uuid);
         KaptchaCodeRequest.setCode(captcha);
         KaptchaCodeResponse KaptchaCodeResponse= ikaptchaService.validateKaptchaCode(KaptchaCodeRequest);
         String code = KaptchaCodeResponse.getImageCode();
         if(!code.equals(SysRetCodeConstants.SUCCESS.getCode())){
             return new ResponseUtil<>().setErrorMsg(KaptchaCodeResponse.getMsg());
         }
         //验证用户和密码
         UserLoginRequest userLoginRequest = new UserLoginRequest();
         userLoginRequest.setPassword(userPwd);
         userLoginRequest.setUserName(userName);
         UserLoginResponse userLoginResponse =loginService.login(userLoginRequest);

         if(userLoginResponse.getCode().equals(SysRetCodeConstants.SUCCESS.getCode())){
             Cookie cookie = CookieUtil.genCookie(TokenIntercepter.ACCESS_TOKEN, userLoginResponse.getToken(), "/", 24 * 60 * 60);
            cookie.setHttpOnly(true);
             response.addCookie(cookie);
             return new ResponseUtil<>().setData(userLoginResponse);
         }
         return new ResponseUtil<>().setData(userLoginResponse.getMsg());
     }
    @GetMapping("/login")
    public ResponseData checkLogin(HttpServletRequest request){
        String userInfo =  (String)request.getAttribute(TokenIntercepter.USER_INFO_KEY);
        Object object = JSON.parse(userInfo);
        return new ResponseUtil<>().setData(object);
    }
}

